import React, {useEffect} from "react";
import {Avatar, Breadcrumb, Button, Dropdown, Flex, MenuProps, message, Modal, Space} from "antd";
import {Header} from "antd/es/layout/layout";
import './index.scss'
import {ExclamationCircleFilled, GithubOutlined, MenuFoldOutlined, MenuUnfoldOutlined} from "@ant-design/icons";
import {useDispatch, useSelector} from "react-redux";
import {StateType} from "@/store";
import {useLocation, useNavigate} from "react-router-dom";
import HeaderItem from "@/components/HeaderItem";
import IconFont from "@/components/IconFont";
import {IconEnum} from "@/utils/IconEnum.ts";
import {logoutAPI} from "@/api/authentication.ts";
import {setToken} from "@/utils/Auth.ts";
import {setMenus} from "@/utils/MuenUtils.tsx";
import {addPath} from "@/store/BreadcrumbSlice.ts";
import {useTranslation} from "react-i18next";
import {changLang} from "@/store/LayoutConfigSlice.ts";

interface IProps {
  collapsed: boolean | undefined
  headerHeight: number | 48 | undefined
  updateCollapsed: (value: boolean) => void
  sideCollapsedWidth?: number
  sideWidth?: number
}

const {confirm} = Modal;

const LayoutHeader: React.FC<IProps> = ({collapsed, headerHeight, updateCollapsed, sideWidth, sideCollapsedWidth}) => {

  const navigate = useNavigate()

  const location = useLocation()

  const dispatch = useDispatch()

  const user = useSelector((state: StateType) => state.pr.userInfo.user)

  const lang = useSelector((state: StateType) => state.pr.layoutConfig.lang)

  const {i18n} = useTranslation();

  //切换语言
  const hdChangeLang = () => {
    if (lang === 'en') {
      i18n.changeLanguage("zh")
      dispatch(changLang("zh"))
    } else {
      i18n.changeLanguage("en")
      dispatch(changLang("en"))
    }
  }

  useEffect(() => {
    // 添加面包屑item
    dispatch(addPath(location.pathname))
  }, [location.pathname])

  const pathArray = useSelector((state: StateType) => state.pr.breadcrumb.pathArray)

  // 显示的面包屑导航路径
  const displayPaths = pathArray.map(p => ({
    title: p.name,
    onClick: () => navigate(p.path)
  }))

  const items: MenuProps['items'] = [
    {label: '个人中心', key: 'UserDetail',},
    {label: '退出登录', key: 'Logout',},
  ];

  const hdClickDropDown: MenuProps['onClick'] = ({key}) => {
    if (key === 'UserDetail') {
      console.log(key)
    } else if (key === 'Logout') {
      confirm({
        title: '确认退出登录？',
        icon: <ExclamationCircleFilled/>,
        content: '点击确认退出登录',
        onOk() {
          logoutAPI().then(res => {
            if (res.code === 200) {
              message.success('注销成功');
              setToken('')
              setMenus([])
              navigate('/login')
            }
          })
        },
      })

    }
  };

  return (
    <Header className="jvyou-layout-header"
            style={{
              height: headerHeight,
              width: `calc( 100% - ${collapsed ? sideCollapsedWidth : sideWidth}px)`,
            }}>
      <Flex justify='start' align='center'>
        <Button type="text" icon={collapsed ? <MenuUnfoldOutlined/> : <MenuFoldOutlined/>}
                onClick={() => updateCollapsed(!collapsed)} className="jvyou-layout-header-collapsed-button"/>
        <Breadcrumb items={displayPaths}/>
      </Flex>

      <Flex align="center" style={{height: headerHeight}} className="jvyou-layout-header-right">
        <Dropdown menu={{items, onClick: hdClickDropDown}} className="jvyou-layout-header-right-item">
          <Space>
            <Avatar src={user.avatar} size={28}/>
            <span>{user.nickName}</span>
          </Space>
        </Dropdown>

        <HeaderItem>
          <GithubOutlined style={{fontSize: 24}}/>
        </HeaderItem>

        <HeaderItem onClick={hdChangeLang}>
          <IconFont icon={IconEnum.LANGUAGE} size={24}/>
        </HeaderItem>
      </Flex>
    </Header>
  )
}

export default LayoutHeader